package modules
{
import core.Configuration;
import core.module.IGameModule;

import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.utils.Dictionary;

import utils.URLUtil;

import values.module.ModuleDataValue;
import values.module.ModuleValue;

/**
 * ModuleBase
 * @author jliang
 *
 */
public class ModuleBase extends Sprite implements IGameModule
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	public function ModuleBase()
	{
		super();
	}
	//==========================================================================
	//  Properties
	//==========================================================================
	protected var configList:Dictionary = new Dictionary(true);
	protected var configLoaded:int = 0;
	protected var isConfigReady:Boolean = false;
	
	protected var _isInited:Boolean = false;
	
	public function get isInited():Boolean
	{
		return _isInited;
	}
	
	protected var vo:ModuleValue;
	
	public function get data():ModuleValue
	{
		return vo;
	}
	
	public function initialize(data:ModuleValue, ...args):void
	{
		vo = data;
		initConfig();
	}
	
	public function checkGameAction(type:String, ...args):void
	{
	}
	
	public function dispose():void
	{
		destory();
	}
	//==========================================================================
	//  Protected methods
	//==========================================================================
	protected function initConfig():void
	{
		if (data.datas.length > 0)
		{
			for each (var obj:ModuleDataValue in data.datas)
			{
				loadConfig(obj.url);
			}
		}
		else
		{
			initConfigComplete();
		}
	}
	
	protected function initConfigComplete():void
	{
		isConfigReady = true;
	}
	
	protected function loadConfig(url:String):void
	{
		var loader:URLLoader = new URLLoader();
		loader.addEventListener(Event.COMPLETE, configLoadedHandler);
		configList[loader] = url;
		loader.load(URLUtil.getRequest(Configuration.moduleDataPath + url));
	}
	
	protected function inited():void
	{
		_isInited = true;
		this.dispatchEvent(new Event(Event.INIT));
	}
	
	protected function destory():void
	{
		_isInited = false;
		this.dispatchEvent(new Event(Event.CLOSE));
	}
	//==========================================================================
	//  Event handlers
	//==========================================================================
	protected function configLoadedHandler(event:Event):void
	{
		var loader:URLLoader = event.target as URLLoader;
		loader.removeEventListener(Event.COMPLETE, configLoadedHandler);
		var url:String = configList[loader];
		delete configList[loader];
		configList[url] = loader.data;
		
		configLoaded ++;
		
		if (configLoaded == data.datas.length)
		{
			initConfigComplete();
		}
	}
}
}



